package com.aidisp.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;



public class HttpUtil {
	private static final int REQUEST_TIMEOUT=10000;
	private static final int RESPONSE_TIMEOUT=30000;
	private static final String CHARACTER = "UTF-8";
	private static final Charset UTFCHARSET = Charset.forName(CHARACTER);
	/**
	 * 发起get方式请求
	 * @param url
	 * @return
	 */
	public String doGet(String url){
		HttpGet httpGet = new HttpGet(url);
		return doExecute(httpGet);
	}
	/**
	 * 将bean转换为json字串，并发起post请求
	 * @param action
	 * @param bean
	 * @return
	 */
	public String doPost4Json(String action,Object bean){
		HttpEntity requestEntity = bean2Json(bean);
		return doPost(action, requestEntity);
	}
	/**
	 * 将bean转换为文本格式的消息体，并发起post请求
	 * @param action
	 * @param bean
	 * @return
	 */
	public String doPost4Text(String action,Object bean){
		HttpEntity requestEntity = null;
		if(bean!=null){
			requestEntity = bean2Entity(bean);
		}
		
		return doPost(action, requestEntity);
	}
	/**
	 * 获取HttpClient连接对象
	 * @return
	 */
	private HttpClient getHttpClient(){
		HttpClient httpClient = new DefaultHttpClient();
		// 设置连接超时
		HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),REQUEST_TIMEOUT);
		// 设置读取超时
		HttpConnectionParams.setSoTimeout(httpClient.getParams(),RESPONSE_TIMEOUT);
		return httpClient;
		
	}
	/**
	 * 发起post请求
	 * @param action
	 * @param requestEntity
	 * @return
	 */
	private String doPost(String action,HttpEntity requestEntity){
		if(action==null){
			throw new NullPointerException();
		}
		HttpPost post = new HttpPost(action);
		post.setEntity(requestEntity);
		return doExecute(post);
	}
	/**
	 * 执行请求,不区分post或是get
	 * @param request
	 * @return
	 */
	private String doExecute(HttpUriRequest request){
		if(request == null){
			throw new NullPointerException();
		}
		HttpClient httpClient = getHttpClient();
		HttpResponse response = null;
		try {
			response = httpClient.execute(request);
			HttpEntity responseEntity = response.getEntity();
			return EntityUtils.toString(responseEntity, UTFCHARSET);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			request.abort();
			httpClient.getConnectionManager().shutdown();
		}
		return null;
	}
	/**
	 * 将对象转为json格式字串
	 * @param bean
	 * @return
	 */
	private HttpEntity bean2Json(Object bean){
		ObjectMapper objectMapper = null;
		ByteArrayOutputStream baos = null;
		JsonGenerator jsonGenerator = null;
	    try {
	    	baos = new ByteArrayOutputStream();
	    	objectMapper = new ObjectMapper();
	    	jsonGenerator = objectMapper.getFactory().createGenerator(baos,JsonEncoding.UTF8);
			jsonGenerator.writeObject(bean);
			baos.flush();
			String entityValue = new String(baos.toByteArray(),"utf-8");
			System.out.println(entityValue);
			return new StringEntity(entityValue,ContentType.APPLICATION_JSON);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(baos!=null){
					baos.close();
				}
				if(jsonGenerator!=null){
					jsonGenerator.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	    return null;
	}
	/**
	 * 将bean转换为文本格式的消息体，只支持简单类型
	 * @param bean
	 * @return
	 */
	private HttpEntity bean2Entity(Object bean){
		Class<?> clazz = bean.getClass();
		Field[] fields = clazz.getDeclaredFields();
		StringBuffer sb = new StringBuffer();
		try {
			for(Field field:fields){
				String fieldName = field.getName();
				String getMethodName = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1, fieldName.length());
				Method getMethod = clazz.getDeclaredMethod(getMethodName);
				Object value = getMethod.invoke(bean);
				sb.append(fieldName+"="+value.toString()+"&");
			}
			sb.deleteCharAt(sb.length()-1);
			return new StringEntity(sb.toString(),UTFCHARSET);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static boolean canConnection(String uri){
		try {
			URL url = new URL(uri);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			System.out.println(conn.getResponseCode());
			conn.disconnect();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
